import {
  ui
} from "~/tools/ui";
import {
  ds
} from "../../../tools/data"
import {
  dsFiles
} from '../../../tools/dsFiles'
import {
  pages
} from '../../../tools/pages'
import {
  storage
} from '../../../tools/storage'

Page({
  data: {
    action: 'new',
    id: '',
    errMsg: '',
    files: [],
    selection: [],
    tag: '',
    totalPage: 1,
    page: 1,
    pageSize: 12,
  },
  async init() {
    const {
      page,
      pageSize
    } = this.data
    const that = this
    const files = ds.coll('files')
    const res = await files.where({
      tag: ds.cmd.neq('avatar')
    }).count()
    const total = res.total || 0
    this.setData({
      totalPage: Math.ceil(total / pageSize)
    })

    files
      .where({
        tag: ds.cmd.neq('avatar')
      })
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()
      .then((res) => {
        const files = res.data
        that.descFiles(files)
        that.setData({
          files,
          selection: [],
          errMsg: ''
        })
        // console.log(res)
        that.data.selection = new Array(res.data.length)
      })
  },
  descFiles(files) {
    for (const file of files) {
      file.desc = dsFiles.nameExt(file.fileId)
      file.type = dsFiles.descFileType(file.fileId)
      file.ext = dsFiles.ext(file.fileId).toUpperCase()
    }
  },
  onPageNumTap(e) {
    const {
      page
    } = e.currentTarget.dataset
    this.setData({
      page
    })
    this.init()
  },
  imgTap(e) {
    const that = this
    // console.log(e.target.dataset.index)
    const idx = e.target.dataset.index
    that.data.selection[idx] = !that.data.selection[idx]
    that.setData({
      selection: that.data.selection
    })
  },
  submitClick() {
    const that = this
    const selFiles = this.selectedFiles();
    // console.log(selFiles)

    pages.back(function (prevPage) {
      prevPage.imgSelected(selFiles, that.data.tag);
    })
  },
  delSelectedClick() {
    this.confirm("确定删除吗？", this.doDelSel)
  },
  uploadImgClick() {
    const {
      totalPage
    } = this.data
    const that = this
    dsFiles.chooseMedia(function (tempFile) {
      dsFiles.uploadFile(tempFile, function (fileId) {
        dsFiles.insert2files(fileId, function (fileId, err) {
          if (fileId) ui.toast(fileId, null, () => {
            that.onPageNumTap({
              currentTarget: {
                dataset: {
                  page: totalPage
                }
              }
            })
          })
        })
      })
    })
  },
  doDelSel() {
    const that = this
    const files2del = that.selectedFiles();

    const swiper = ds.coll('files')
    try {
      swiper.where({
        fileId: ds.cmd.in(files2del)
      }).remove();

      wx.cloud.deleteFile({
        fileList: files2del
      }).then(res => {
        that.onLoad();
      }).catch(error => {
        wx.showToast({
          title: '删除失败',
          icon: 'fail',
          duration: 1000,
          mask: true
        })
      })
    } catch (e) {
      console.error(e)
    }
  },
  selectedFiles() {
    const {
      files,
      selection
    } = this.data
    const sel = selection
    const resFiles = []
    for (let idx in sel) {
      if (sel[idx]) resFiles.push(files[idx].fileId)
    }

    return resFiles
  },
  confirm(msg, action) {
    wx.showModal({
      title: '提示',
      content: msg,
      success: function (res) {
        if (res.confirm) action();
      }
    })
  },
  onLoad(option) {
    if (option) {
      if (option.action) {
        this.setData({
          action: option.action, // new
          id: option.id
        })
      }

      if (option.tag) {
        const tag = option.tag
        this.setData({
          tag
        })
      }
    }

    this.init();
  },
});